<?php
namespace recite\controllers;

use app\models\Knowledge;
use common\libraries\Collector;
use common\libraries\File;
use common\models\Article;
use recite\models\Site;
use Yii;
use common\components\PageView;
use common\models\Category;

/**
 * ArticleController
 */
class ArticleController extends Controller{

    public $enableCsrfValidation = false;

    public function actionList(){

        $c1 = isset($_GET["c1"]) ? intval($_GET["c1"]) : 0;
        $c2 = isset($_GET["c2"]) ? intval($_GET["c2"]) : 0;
        $c3 = isset($_GET["c3"]) ? intval($_GET["c3"]) : 0;
        $cid = isset($_GET["cid"]) ? intval($_GET["cid"]) : 0;
        $graduated = isset($_GET["graduated"]) ? intval($_GET["graduated"]) : 1;
        $mobile = (isset($_GET["mobile"]) && strtolower($_GET["mobile"]) != 'false') ? true : false;

        $categorys = \common\models\Category::getData();
        //print_r($categorys);

        $treeData = \common\models\Category::getTree($categorys);
        //print_r($treeData);

        $where = " WHERE TRUE";
        $con1 = ($c1 == 0) ? "" : " AND k.c1=".$c1;
        $con1 = ($c2 == 0) ? $con1 : " AND k.c2=".$c2;
        $con1 = ($c3 == 0) ? $con1 : " AND k.c3=".$c3;
        $con2 = ($graduated == 1) ? " AND k.graduated=0" : "";
        $where = $where.$con1.$con2;

        $db = Yii::$app->db;
        $dataCount = $db->createCommand('SELECT count(*) as dataCount FROM recite_article AS k'.$where)->queryScalar();

        $perPage = 20;
        $currentPage = isset($_GET["page"]) ? intval($_GET["page"]) : 1;

        $pv = new PageView($dataCount, $perPage, $currentPage);

        $sql = 'SELECT k.id, k.cid, k.question, k.answer, k.`right`, t.name AS tname, c2.name AS cname2, k.last_right_time FROM recite_article AS k '.
            'LEFT JOIN recite_knowledge_category AS t ON k.c1=t.id '.
            'LEFT JOIN recite_knowledge_category AS c2 ON k.c2=c2.id'.
            $where." ORDER BY k.id ASC".$pv->limitSql;

        $knowledge =  $db->createCommand($sql)->queryAll();

        $data = [
            "c1" => $c1,
            "c2" => $c2,
            "c3" => $c3,
            "cid" => $cid,
            "categorys" => $categorys,
            'treeData' => $treeData,
            "graduated" => $graduated,
            "knowledge"=> $knowledge,
            "pv"=>$pv,
            "mobile"=>$mobile,
        ];

        if($mobile){
            return $this->renderPartial('mobile', $data);
        }else{
            return $this->renderPartial('list', $data);
        }

    }

    public function actionEdit(){

        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;

        $categorys = Category::getData();
        $treeData = Category::getTree($categorys);

        $db = Yii::$app->db;
        $sql = "SELECT `c1`, `c2`, `c3`, `id`,`cid`,`question`,`answer` FROM recite_article WHERE id=$id";

        $knowledge = $db->createCommand($sql)->queryOne();

        $data = [
            "id" => $id,
            "treeData" => $treeData,
            "knowledge" => $knowledge,
        ];
        return $this->renderPartial('edit', $data);
    }

    public function actionAsyncEdit(){
        $id = isset($_POST["id"]) ? intval($_POST["id"]) : 0;
        $c1 = isset($_POST["c1"]) ? intval($_POST["c1"]) : 0;
        $c2 = isset($_POST["c2"]) ? intval($_POST["c2"]) : 0;
        $c3 = isset($_POST["c3"]) ? intval($_POST["c3"]) : 0;
        $cid = isset($_POST["cid"]) ? intval($_POST["cid"]) : 0;
        $question = isset($_POST["question"]) ? addslashes($_POST["question"]) : 0;

        //内容
        $content = isset($_POST["content"]) ? strval($_POST["content"]) : 0;
        $content = preg_replace('/[\r\n]/', '', $content);//去换行
        $content = preg_replace('/\<\!--.*?--\>/i', '', $content);//去掉注释
        $content = preg_replace('/\s{2,}/', ' ', $content);//多个空格换成一个空格
        $content = preg_replace('/<script.*?>[\s\S]*?<\/script>/', ' ', $content);//去JS

        $content = preg_replace_callback('/<img[^<>]*?src=\"(.*?)\"[^<>]*?>/', function($matches){

            //如果匹配到图片
            if(isset($matches[1]) && !empty($matches[1])){
                $urlFile = $matches[1];
                if(preg_match('/^http/i', $urlFile)){
                    preg_match('/\.\w+?$/', $urlFile, $matches);
                    $postfix = isset($matches[0]) ? $matches[0] : "";
                    $postfix = empty($postfix) ? ".png" : $postfix;
                    $filename = Collector::randStr(10) . $postfix;
                    $web_root = Site::getWebRoot();
                    $file_uri = '/data/uploads/article' . date('/Ym/d') . "/" . $filename;
                    $saveFile = $web_root . $file_uri;

                    try{
                        File::download($urlFile, $saveFile);
                    }catch (\Exception $e){
                        return '';
                    }
                    return '<img src="'.$file_uri.'">';
                }
            }
            return $matches[0];
        }, $content);
        $content = addslashes($content);

        $columns = [
            'c1' => $c1,
            'c2' => $c2,
            'c3' => $c3,
            'cid' => $cid,
            'question' => $question,
            'answer' => $content,
        ];

        try{
            if(empty($id)){
                $knowledge = new Article();
                $knowledge->setAttributes($columns);
                if($knowledge->save()){
                    exit(json_encode(["code"=>1, "info"=>"添加成功", "id"=>$knowledge->id], JSON_UNESCAPED_UNICODE));
                }else{
                    exit(json_encode(["code"=>-3, "info"=>"添加失败"], JSON_UNESCAPED_UNICODE));
                }
            }else{
                Article::updateAll($columns, ['id'=>$id]);
                exit(json_encode(["code"=>1, "info"=>"编辑成功"], JSON_UNESCAPED_UNICODE));
            }
            exit(json_encode(["code"=>1, "info"=>"编辑成功"], JSON_UNESCAPED_UNICODE));
        }catch (\Exception $e){
            exit(json_encode(["code"=>-3, "info"=>"编辑失败", 'exception'=>$e->getMessage()], JSON_UNESCAPED_UNICODE));
        }
    }

    public function actionDetail(){
        $id = isset($_GET["id"]) ? intval($_GET["id"]) : 0;


        if(empty($id)){
            exit("no id");
        }

        $article = Article::find()->where(["id"=>$id])->asArray()->one();

        $data = [
            "id" => $id,
            "article" => $article,
        ];
        return $this->renderPartial('detail', $data);

    }


}
